package com.server.http.handler.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.server.ServerUtils;
import com.server.background.data.App;
import com.server.background.data.OPPOPayReqResp;
import com.server.background.data.Store;
import com.server.conditionenum.HttpReturnStatus;
import com.server.db.DataBaseManager;
import com.server.http.handler.HttpHandler;
import com.server.http.request.HttpRequestMessage;
import com.server.http.response.HttpResponseMessage;
import com.server.mine.net.HttpProtocol;
import com.server.tools.AESTools;
import com.server.tools.OPPOMiniPay;
import com.server.tools.RedeemCode;

public class Client_OPPOPayReq extends HttpHandler{
	@Override
	public void handle(HttpRequestMessage request, HttpResponseMessage response) {
		int status = 0;
		OPPOPayReqResp resp = new OPPOPayReqResp();
		
		String data = request.getParameter("data");
		data = AESTools.AESDecrypt(data);
		String[] datas = data.split("\\|");
		
		//应用编号
		int appid = Integer.parseInt(datas[0]);
		//商品编号
		int item_id = Integer.parseInt(datas[1]);
		//应用版本
		String app_version = datas[2];
		//用户编号
		//int uid = Integer.parseInt(datas[3]);
		//登录凭据
		String token = datas[4];
		//引擎版本
		String en_version = datas[5];
		//时间戳
		Long timestamp = System.currentTimeMillis();
		App app = DataBaseManager.GetInstance().GetApp(appid);
		Store store = ServerUtils.store_map.get(item_id);
		if(app != null && store != null) {
			String order_id = RedeemCode.create((byte)1,1,12,RedeemCode.defaut_password)[0];
			String order_str = OPPOMiniPay.SendOrder(app.wx_appid, token, store.name, store.desc, 1, store.price, order_id, app_version, en_version, timestamp);
			JSONObject order = JSON.parseObject(order_str);
			if(order.get("code").equals("200") && order.get("msg").equals("success")) {
				String oppo_order_id = JSON.parseObject(order.getString("data")).getString("orderNo");
				String sign = OPPOMiniPay.GetPaySignature(app.wx_secret, oppo_order_id, timestamp);
				resp.o_order = oppo_order_id;
				resp.sign = sign;
				resp.timestamp = timestamp;
				resp.appid = app.wx_appid.toString();
				status = 1;
			}else {
				status = -1;
			}
		}else {
			status = -1;
		}
		
		if(status == 1) {
			SetReturnData(response,resp,HttpProtocol.OPPOPAYREQ,HttpReturnStatus.Successed);
		}else {
			SetReturnData(response,"申请订单失败",HttpProtocol.OPPOPAYREQ,HttpReturnStatus.Failed);
		}
	}
}
